//
//  DocumentsViewController.m
//  Documents
//
//  Created by Alex Di Mango 
//  Copyright (c) 2012 Whardoo.com -  All rights reserved.
//

#import "DocumentsViewController.h"
#import "DocumentThumbView.h"
#import "FolderThumbView.h"
#import "DocumentsColors.h"
#import "DocumentsCache.h"
#import "DocumentsConstants.h"
#import "DocumentsInfoViewController.h"
#import "MyDocument.h"
#import "NSObject+PerformBlockAfterDelay.h"
#import <QuartzCore/QuartzCore.h>
#import "NSObject+ThumbViewMaker.h"

@implementation DocumentsViewController
@synthesize markedImage;
@synthesize selectedDocument;
@synthesize selectedFolder,currentFolder;
@synthesize selectedImage;
@synthesize selectedImageRef;
@synthesize selectedTitle;
@synthesize tagColor1;
@synthesize tagColor2;
@synthesize tagColor3;
@synthesize tagColor4;
@synthesize selectedType;
@synthesize selectedUpdatedate;
@synthesize selectedSize;
@synthesize selectedBorder;
@synthesize masterView;
@synthesize idFolder,idDoc;
@synthesize itemDocList=_itemDocList;
@synthesize itemFolderList=_itemFolderList;
@synthesize infoPopover,freeSpaceLabel,docToolbar;
@synthesize thumbWebView,loadedThumbWebView,activityView;
@synthesize uploadDocument,uploadDocumentPath,didEnterBackground,didDragged;
@synthesize isScrolling;
@synthesize didUrlOpening;
@synthesize loadedWebView;

// image reflection
static const CGFloat kDefaultReflectionFraction = 0.20;
static const CGFloat kDefaultReflectionFraction_f = 0.30;
static const CGFloat kDefaultReflectionOpacity = 0.40;


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
  }

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setTag:999];
    self.view.autoresizesSubviews = NO;
    
//    CAGradientLayer *gradient = [CAGradientLayer layer];
//    gradient.frame = CGRectMake(0,0, 1024, 768);
//    gradient.colors = [NSArray arrayWithObjects:(id)[BLACK CGColor], (id)[BLACK_GRADIENTE CGColor], nil];
//    [self.view.layer insertSublayer:gradient atIndex:0];    
//    
	// Do any additional setup after loading the view, typically from a nib.
    //subscribe notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMaster) name:REFRESH_FOLDERS_AND_DOCS object:nil];       
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkIfLaunchingWithOptions) name:APP_ACTIVE_CHECK object:nil];      
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshFreeSpace) name:REFRESH_FREE_SPACE object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMarked) name:REFRESH_MARKED object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetRefreshStatus) name:UIApplicationDidBecomeActiveNotification object:nil];

    UIButton *a1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [a1 setFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];
    [a1 addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
    [a1 setImage:[UIImage imageNamed:@"info.png"] forState:UIControlStateNormal];
    UIBarButtonItem *random = [[UIBarButtonItem alloc] initWithCustomView:a1];
        
    self.navigationItem.rightBarButtonItem = random;
    
    DocumentsInfoViewController *infoView = [[DocumentsInfoViewController alloc]initWithNibName:@"DocumentsInfoViewController" bundle:nil];
    UIPopoverController *infoPopoverController = [[UIPopoverController alloc]initWithContentViewController:infoView];
    self.infoPopover = infoPopoverController;
    
 //   [infoView release];
 //   [infoPopoverController release];
    [self.infoPopover setPopoverContentSize:CGSizeMake(300, 600)];

    self.freeSpaceLabel = [[UILabel alloc]initWithFrame:CGRectMake(905, 0, 110, self.navigationController.toolbar.frame.size.height)];
    self.freeSpaceLabel.textColor = [UIColor whiteColor];
    self.freeSpaceLabel.font = [UIFont systemFontOfSize:12];
    self.freeSpaceLabel.backgroundColor = [UIColor clearColor];
    self.freeSpaceLabel.lineBreakMode = UILineBreakModeWordWrap;
    self.freeSpaceLabel.numberOfLines = 2;
    self.freeSpaceLabel.textAlignment = UITextAlignmentRight;
    [self refreshFreeSpace];
    [self.navigationController.toolbar addSubview:freeSpaceLabel];
    self.masterView.showsVerticalScrollIndicator = YES;
    self.masterView.autoresizesSubviews = NO;
    
    
    [self setLoadedThumbWebView:YES];
    [self checkIfLaunchingWithOptions];      

    //folder color tag
    [self tagButton:NO];
    tagColor1.layer.borderWidth = 1.0;
    tagColor1.layer.borderColor = [[UIColor grayColor]CGColor];
    tagColor2.layer.borderWidth = 1.0;
    tagColor2.layer.borderColor = [[UIColor grayColor]CGColor];
    tagColor3.layer.borderWidth = 1.0;
    tagColor3.layer.borderColor = [[UIColor grayColor]CGColor];
    tagColor4.layer.borderWidth = 1.0;
    tagColor4.layer.borderColor = [[UIColor grayColor]CGColor];
}

-(void)tagButton:(BOOL)enable{
    if(enable){
        tagColor1.enabled = YES;
        tagColor1.alpha = 1.0;   
        tagColor2.enabled = YES;
        tagColor2.alpha = 1.0;  
        tagColor3.enabled = YES;
        tagColor3.alpha = 1.0;  
        tagColor4.enabled = YES;
        tagColor4.alpha = 1.0;  
    }else {
        tagColor1.enabled = NO;
        tagColor1.alpha = 0.4;   
        tagColor2.enabled = NO;
        tagColor2.alpha = 0.4;  
        tagColor3.enabled = NO;
        tagColor3.alpha = 0.4;  
        tagColor4.enabled = NO;
        tagColor4.alpha = 0.4;  
    }
}

#pragma mark - Opening with options

-(void)checkIfLaunchingWithOptions
{
    AppDelegate *delegate= (AppDelegate*)[[UIApplication sharedApplication] delegate];

    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"firstTime"] == NULL) {
        [[NSUserDefaults standardUserDefaults] setValue:@"Not" forKey:@"firstTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    //Add documents folder    
        NSManagedObjectContext *managedObjectContext = [delegate managedObjectContext];
        MyDocumentsFolder *folder = (MyDocumentsFolder *)[NSEntityDescription insertNewObjectForEntityForName:@"MyDocumentsFolder" inManagedObjectContext: managedObjectContext];
        [folder setFolderId: [NSNumber numberWithInt:1]];
        [folder setDefaultFolder:[NSNumber numberWithInt:1]];
        [folder setName:@"Documents"];
    //Add example pdf    
        NSArray *pdfs = [[NSBundle mainBundle] pathsForResourcesOfType:@"pdf" inDirectory:nil];
        NSString *filePath = [pdfs lastObject];
        [MyDocument addDocument:[NSURL fileURLWithPath:filePath]];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];    
        
    }
    
    uploadDocumentPath = [delegate uploadDocumentPath];

    if([[delegate uploadDocumentPath] isFileURL]){
        
    [MyDocument addDocument:[self uploadDocumentPath]];
    
        NSString *filePath = [[self uploadDocumentPath]path];
        NSFileManager *fileManager = [NSFileManager defaultManager];  
        if ([fileManager fileExistsAtPath:filePath]) 
        {
            NSError *error;
            if (![fileManager removeItemAtPath:filePath error:&error])
            {
                NSLog(@"ERROR removing file: %@", error); 
            };
        } else {
            NSLog(@"ERROR (File not found): %@",filePath); 
        }
    
    [self setUploadDocumentPath:nil];    
    [delegate setUploadDocumentPath:nil];   
    [self setSelectedFolder:[MyDocumentsFolder getDefaultFolder]];    
    [self setDidUrlOpening:YES];
    [self tagButton:NO];
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];    
    
    }
    [self refreshDocuments];
    [self reloadData];
    [self refreshFreeSpace];
    
    if(didUrlOpening){
        //chiedo max doc id, prendo la view e simulo tocco.
        int lastDocId = [[MyDocument getMaxDocumentId]intValue];
        [masterView showDocument:[NSNumber numberWithInt:lastDocId]];
    
        [self setDidUrlOpening:NO];
    
    }
}

-(void)EnterBackground
{
    [self setDidEnterBackground:YES];
}

-(void)modalClose{
    [self.parentViewController dismissModalViewControllerAnimated:YES];
}


-(void)resetRefreshStatus
{
    AppDelegate *delegate= (AppDelegate*)[[UIApplication sharedApplication] delegate];
    uploadDocumentPath = [delegate uploadDocumentPath];
    if([[delegate uploadDocumentPath] isFileURL]){
        
        [self.parentViewController dismissModalViewControllerAnimated:YES];
        [MyDocument addDocument:[self uploadDocumentPath]];
        NSString *filePath = [[self uploadDocumentPath]path];
        NSFileManager *fileManager = [NSFileManager defaultManager];  
        if ([fileManager fileExistsAtPath:filePath]) 
        {
            NSError *error;
            if (![fileManager removeItemAtPath:filePath error:&error])
            {
                NSLog(@"ERROR removing file: %@", error); 
            };
        } else {
            NSLog(@"ERROR (File not found): %@",filePath); 
        }
        [self setUploadDocumentPath:nil];    
        [delegate setUploadDocumentPath:nil];   
        [self setSelectedFolder:[MyDocumentsFolder getDefaultFolder]];    
        [self setDidUrlOpening:YES];
        [self tagButton:NO];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];    
        [self refreshDocuments];
        [self reloadData];
        [self refreshFreeSpace];
        if(didUrlOpening){
            int lastDocId = [[MyDocument getMaxDocumentId]intValue];
            [self performBlock:^{
                [masterView showDocument:[NSNumber numberWithInt:lastDocId]];
       
            } afterDelay:0.5];
            [self setDidUrlOpening:NO];
        } 
    }
}


-(void)refreshSelected{
    if(selectedDocument!=nil){
    DocumentThumbView *docThumb = (DocumentThumbView *)[self.masterView viewWithTag:[selectedDocument.documentId intValue]];
    if(docThumb!=nil){
        [self setSelectedBorder:docThumb];    
        [self.selectedBorder drawSelectionRect];
    }
    }
}
#pragma mark -  Marked Button tap

-(void)refreshMarked
{
    [self.markedImage setImage:[UIImage imageNamed:[self.selectedDocument.marked boolValue] ? @"Mark-Y" :@"Mark-N"] forState:UIControlStateNormal];
    
    for (UIView *subview in self.masterView.subviews) {
        if ([subview isKindOfClass:[DocumentThumbView class]]) {
            if ([[NSNumber numberWithInt:subview.tag]intValue]==[selectedDocument.documentId  intValue]) {
                DocumentThumbView *view = (DocumentThumbView *)subview; 
                if([selectedDocument.marked boolValue]){
                    if(view.docMarked==nil){
                        view.docMarked = [[UIImageView alloc]initWithFrame:CGRectMake(111, 5, 10., 16.)];
                        view.docMarked.image = [UIImage imageNamed:@"Mark-Y"];
                        view.docMarked.tag = 333;
                        [UIView animateWithDuration:0.2 animations:^{
                            [view addSubview:view.docMarked];
                        }];                        
                    }
                }else {
                    if(view.docMarked!=nil){
                        view.docMarked = nil;
                        [UIView animateWithDuration:0.2 animations:^{
                            UIView *docMarked = [view viewWithTag:333];
                            [docMarked removeFromSuperview];
                        }];    
                    }                    
                }
                [self.masterView setNeedsDisplay];
            }
            }
    }
}

-(IBAction)changeMarkedState:(id)sender
{
    [self.selectedDocument setMarked:[NSNumber numberWithBool:![self.selectedDocument.marked boolValue]]];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate saveContext];
    [self refreshMarked];
}

- (IBAction)setFolderColor:(id)sender {
    UIButton *colorTag = sender;
    FolderThumbView *myFolder = (FolderThumbView *)[masterView viewWithTag:[selectedFolder.folderId  intValue]];
                [selectedFolder setColor:[NSString stringWithFormat:@"%d", colorTag.tag]];
                myFolder.folderImage.alpha = 0;
                myFolder.folderRefImage.alpha = 0;
                self.selectedImageRef.alpha = 0.;
                self.selectedImage.alpha = 0.;
                myFolder.folderImage.image = [UIImage imageNamed:[NSString stringWithFormat:[NSString stringWithFormat:@"%d%@", colorTag.tag,@"-folder",nil]]];
                NSUInteger reflectionHeight = myFolder.folderImage.bounds.size.height * kDefaultReflectionFraction_f;
                myFolder.folderRefImage.image = [myFolder reflectedImage:myFolder.folderImage withHeight:reflectionHeight];
                self.selectedImage.image = [UIImage imageNamed:[NSString stringWithFormat:[NSString stringWithFormat:@"%d%@", colorTag.tag,@"-folderSelected",nil]]];
                self.selectedImageRef.image = [self reflectedImage:self.selectedImage withHeight:70];
                [UIView animateWithDuration:0.2 animations:^{
                    myFolder.folderImage.alpha = 1;
                    myFolder.folderRefImage.alpha = 0.8;
                    self.selectedImageRef.alpha = 0.8;
                    self.selectedImage.alpha = 1;
                }];    
            }

#pragma mark - Rename tapped

-(void)refreshMaster{
    [self refreshDocuments];
    [self reloadData];
    [self refreshSelected];
    [self.masterView setNeedsDisplay];
}


- (void)tappedAddFolder
{
    
    UIAlertView *msg = [[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"newFolder", @"Documents", nil) message:NSLocalizedStringFromTable(@"newFolderMsg", @"Documents", nil) delegate:self
                                       cancelButtonTitle:NSLocalizedStringFromTable(@"cancel", @"Documents", nil) otherButtonTitles:NSLocalizedStringFromTable(@"create", @"Documents", nil), nil ];   
    [msg setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [msg show];    
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == alertView.firstOtherButtonIndex) 
    {    
    if([MyDocumentsFolder getFolderWithName:[[alertView textFieldAtIndex:0] text] andFolderId:nil]!=nil){
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"error", @"Documents", nil) message:[NSString stringWithFormat:NSLocalizedStringFromTable(@"nameError", @"Documents", nil),[[alertView textFieldAtIndex:0] text]] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }
    else {
            MyDocumentsFolder *folder = [MyDocumentsFolder addFolder:[[alertView textFieldAtIndex:0] text]];
            [folder setCreateDate:[NSDate date]];
        [self setSelectedFolder:[MyDocumentsFolder getDefaultFolder]];
            [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];
        [self refreshMaster];
        }
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    NSString *inputText = [[alertView textFieldAtIndex:0] text];
    if( [inputText length] >= 1 )
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


#pragma mark - UIWebviewdelegate Thumb

-(void)getMSDetailThumb:(NSURL *)documentURL{
    NSLog(@"GET IMAGE");
    thumbWebView = [[UIWebView alloc]init];
    [thumbWebView sizeToFit];
    thumbWebView.backgroundColor = [UIColor whiteColor];
    thumbWebView.scalesPageToFit = YES;
    thumbWebView.frame = CGRectMake(882., 31, 240., 339.);
    thumbWebView.delegate = self;
    thumbWebView.tag = [self.selectedDocument.documentId intValue];
    NSURLRequest *request = [NSURLRequest requestWithURL:documentURL];
    [self setLoadedThumbWebView:NO];    
    [thumbWebView loadRequest:request];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
        
    if(!loadedThumbWebView){
    if (webView.tag == [self.selectedDocument.documentId intValue]) {
    UIGraphicsBeginImageContext(CGSizeMake(240.,339.));
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[[self thumbWebView] layer] renderInContext:context];
        self.selectedImage.alpha = 0;
        self.selectedImageRef.alpha = 0;
        [UIView animateWithDuration:0.5 animations:^{
            UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            self.selectedImage.image = thumbnail;
            self.selectedImageRef.image = [self reflectedImage:self.selectedImage withHeight:50];
            self.selectedImageRef.alpha = 0.8;
            self.selectedImage.alpha = 1;
            [self refreshMarked];
            [[self markedImage]setHidden:NO];
            [activityView stopAnimating];
            self.activityView = nil;
        }];    
        [self setLoadedThumbWebView:YES];    
        NSData *sideImageData = UIImagePNGRepresentation(self.selectedImage.image);
        NSData *sideImageRefData = UIImagePNGRepresentation(self.selectedImageRef.image);
        [self.selectedDocument setValue:sideImageData forKey:@"sideImage"];
        [self.selectedDocument setValue:sideImageRefData forKey:@"sideImageRef"];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];  
    }
    }
}

//The event handling method
- (void)handleSingleTap:(UITouch *)touch {
//    CGPoint offset = [masterView contentOffset];
//    CGSize size = [masterView contentSize];
//    
//    NSLog(@" OFFSET %@   SIZE %@", NSStringFromCGPoint(offset),NSStringFromCGSize(size));    
    
    UIView *tapped = touch.view;
    
    if ([tapped isKindOfClass:[FolderThumbView class]])
    {
        MyDocumentsFolder *myFolder = [MyDocumentsFolder getFolderWithId:[NSNumber numberWithInt:tapped.tag]];
        [self setSelectedFolder:myFolder];
        [self setSideFolder:myFolder];
        [self setSelectedDocument:nil];  
        if (myFolder.folderId!=[NSNumber numberWithInt:1]) {
            [self tagButton:YES];
        }else {
            [self tagButton:NO];            
        }
        if(selectedBorder!=nil){
            UIView *view = [self.selectedBorder viewWithTag:888];
            [view removeFromSuperview];
        } 
    }
    else{
        MyDocument *myDoc = [MyDocument getDocumentWithId:[NSNumber numberWithInt:tapped.tag]];
        if(selectedBorder!=nil){
            UIView *view = [self.selectedBorder viewWithTag:888];
            [view removeFromSuperview];
        } 
        [self setSelectedBorder:(DocumentThumbView *)tapped];
        [self setSelectedDocument:myDoc];
        [self setSideDocument:myDoc];
        [self tagButton:NO];
       }
}

-(void)setSideDocument:(MyDocument *)document{
    [[self markedImage]setHidden:YES];
    self.selectedImage.image = nil;
    self.selectedImageRef.image = nil;
    self.selectedTitle.numberOfLines = 2;
    self.selectedTitle.text= document.title;
    NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
    [f2 setDateFormat:@"EEEE d MMMM YYYY HH:mm"];
    NSString *s = [f2 stringFromDate:document.updateDate];
    self.selectedUpdatedate.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedStringFromTable(@"lastOpened", @"Documents", nil),s];
    self.selectedType.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedStringFromTable(@"kind", @"Documents", nil),
                              NSLocalizedStringFromTable(document.fileType, @"Documents", nil)];                        
                              
    self.selectedType.numberOfLines = 2;

    self.selectedSize.text = [NSString stringWithFormat:@"%@ %d %@",NSLocalizedStringFromTable(@"size", @"Documents", nil), [document.size intValue], NSLocalizedStringFromTable(@"kb", @"Documents", nil)];
        
    [self.selectedBorder drawSelectionRect];
    
    NSString *localFilePath = [DocumentsCache localFilePathFromDoc:document];
    NSString *newURL = [[NSString stringWithFormat:@"file://localhost%@",localFilePath] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
    
    if([document sideImage]!=nil){
        self.selectedImage.alpha = 0.;
        self.selectedImageRef.alpha = 0.;
        [UIView animateWithDuration:0.2 animations:^{
            self.selectedImage.alpha = 1;
            self.selectedImage.image = [UIImage imageWithData:[document valueForKey:@"sideImage"]];
            self.selectedImageRef.image = [self reflectedImage:self.selectedImage withHeight:50];
            self.selectedImageRef.alpha = 0.8;
            [self refreshMarked];
            [[self markedImage]setHidden:NO];
        }];  
    }else {

        if([[document fileType]isEqualToString:@"pdf"]||[[document fileType]isEqualToString:@"pages"]){
        
        if (activityView == nil)
        {
            activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            activityView.hidesWhenStopped = YES;
            activityView.center = CGPointMake(120,150);
            activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
            [self.selectedImage addSubview:activityView];
        }
        [activityView startAnimating];
        self.selectedImage.alpha = 0.;
        self.selectedImageRef.alpha = 0.;
      
        [UIView animateWithDuration:0.2 animations:^{
            self.selectedImage.alpha = 1;
            self.selectedImage.image = [self getThumb:newURL setW:240 setH:339];
         self.selectedImageRef.image = [self reflectedImage:self.selectedImage withHeight:50];
            self.selectedImageRef.alpha = 0.8;
            [activityView stopAnimating];
            [self refreshMarked];
            [[self markedImage]setHidden:NO];
        }];  
        NSData *sideImageData = UIImagePNGRepresentation(self.selectedImage.image);
        NSData *sideImageRefData = UIImagePNGRepresentation(self.selectedImageRef.image);
        [document setValue:sideImageData forKey:@"sideImage"];
        [document setValue:sideImageRefData forKey:@"sideImageRef"];
        [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];  
        
    }      
    else {
        if (activityView == nil)
        {
            activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            activityView.hidesWhenStopped = YES;
            activityView.center = CGPointMake(120,169.5);
            activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
            self.selectedImage.image = nil;
            self.selectedImageRef.image = nil;
            [self.selectedImage addSubview:activityView];
        }
        [activityView startAnimating];
        NSLog(@"Set side document.");
        [self getMSDetailThumb:[NSURL URLWithString:newURL]]; 
    }
        
    }      

}


-(void)setSideFolder:(MyDocumentsFolder *)folder{
    [[self markedImage]setHidden:YES];
    self.selectedImageRef.alpha = 0.;
    self.selectedImage.alpha = 0.;
    if(folder.folderId==[NSNumber numberWithInt:1] ){
        self.selectedImage.image = [UIImage imageNamed:@"defaultFolderSelected"];
        self.selectedImageRef.image = [self reflectedImage:self.selectedImage withHeight:70];
    }else {
        
        if(folder.color!=nil){
            self.selectedImage.image = [UIImage imageNamed:[NSString stringWithFormat:[NSString stringWithFormat:@"%@%@", folder.color,@"-folderSelected",nil]]];
        }
        else {
            self.selectedImage.image = [UIImage imageNamed:@"0-folderSelected"];
        }      
        self.selectedImageRef.image = [self reflectedImage:self.selectedImage withHeight:70];        
    }
       
        [UIView animateWithDuration:0.2 animations:^{
            self.selectedImageRef.alpha = 0.8;
            self.selectedImage.alpha = 1;
            [activityView stopAnimating];
            self.activityView = nil;
        }];    
    self.selectedTitle.numberOfLines = 2;
    self.selectedTitle.text= folder.name;
    
    self.selectedType.text= @"Kind: Folder";
    NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
    [f2 setDateFormat:@"EEEE d MMMM YYYY HH:mm"];
    NSString *s = [f2 stringFromDate:folder.createDate];
    self.selectedUpdatedate.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedStringFromTable(@"lastOpened", @"Documents", nil),s];
    NSSet *docs = [folder documents];    
    int size = 0;
    for (MyDocument *doc in docs) {
        size = size +[doc.size intValue];
    }
    self.selectedSize.text = [NSString stringWithFormat:@"%@ %d %@ for %@",NSLocalizedStringFromTable(@"size", @"Documents", nil),size, NSLocalizedStringFromTable(@"kb", @"Documents", nil),[self getDocumentsNumber:[folder.documents count]]];
}

-(void)showInfo
{    
    [self.infoPopover presentPopoverFromBarButtonItem:[self.navigationItem rightBarButtonItem]
                             permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

-(void)refreshDocuments
{  
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];     
   //remove all subviews
    
    for (UIView *subview in masterView.subviews) {
        if ([subview isKindOfClass:[DocumentThumbView class]]||[subview isKindOfClass:[FolderThumbView class]]) {
            [subview removeFromSuperview];
        }        
     }
        
    //qui devo gestire se home o no e il dettaglio che sarà presentato.
    //Posso usare selectedFolder and selectedDoc
    if(didDragged){
        if(selectedFolder.folderId==[NSNumber numberWithInt:1]){
            [self tagButton:NO];
            _itemFolderList = [MyDocumentsFolder getFolderList];
            _itemDocList = [MyDocument getDocumentListWithName:nil forFolder:[NSNumber numberWithInt:1] orderBy:@"title" ascending:YES];  
            [self setSideFolder:[MyDocumentsFolder getDefaultFolder]];
        } else {
            _itemFolderList = [NSArray arrayWithObject:[MyDocumentsFolder getDefaultFolder]];   
            _itemDocList = [MyDocument getDocumentListWithName:nil forFolder:selectedFolder.folderId orderBy:@"title" ascending:YES];
            [self setSideFolder:selectedFolder];
            [self tagButton:YES];

        }
        
        [self setDidDragged:NO];
    }else {
    if(selectedDocument!=nil){
        MyDocumentsFolder *myFolder = selectedDocument.myFolder;
        _itemDocList = [MyDocument getDocumentListWithName:nil forFolder:myFolder.folderId orderBy:@"title" ascending:YES];
            [self setSideDocument:selectedDocument];   
        if(myFolder.folderId == [NSNumber numberWithInt:1]){
        _itemFolderList = [MyDocumentsFolder getFolderList];
        }else {
        _itemFolderList = [NSArray arrayWithObject:[MyDocumentsFolder getDefaultFolder]];   
        }
    }else {
       if(selectedFolder.folderId==[NSNumber numberWithInt:1] || selectedFolder==nil){
        MyDocumentsFolder *myFolder = [MyDocumentsFolder getDefaultFolder];
        [myFolder setCreateDate:[NSDate date]]; 
           [self tagButton:NO];   
        [self setSideFolder:myFolder];
        _itemFolderList = [MyDocumentsFolder getFolderList];
        _itemDocList = [MyDocument getDocumentListWithName:nil forFolder:[NSNumber numberWithInt:1] orderBy:@"title" ascending:YES];   
       }else {
        [self setSideFolder:selectedFolder]; 
        _itemFolderList = [NSArray arrayWithObject:[MyDocumentsFolder getDefaultFolder]]; 
        _itemDocList = [MyDocument getDocumentListWithName:nil forFolder:selectedFolder.folderId orderBy:@"title" ascending:YES];
       }
    }
    }
    if(selectedFolder.folderId == [NSNumber numberWithInt:1] || selectedFolder==nil){
        self.navigationItem.title = NSLocalizedStringFromTable(@"myDocumentsTitle", @"Documents", nil);
        //setup navigation bar
        UIBarButtonItem *leftBarButton = [UIBarButtonItem new];
        [leftBarButton setTitle:NSLocalizedStringFromTable(@"newFolder", @"Documents", nil)];
        [leftBarButton setTarget:self];
        [leftBarButton setAction:@selector(tappedAddFolder)];
        [self.navigationItem setLeftBarButtonItem:leftBarButton];
    }else {
        self.navigationItem.title = selectedFolder.name;        
        self.navigationItem.leftBarButtonItem=nil;
    }
}

-(void)backToHome{
    [self setSelectedFolder:[MyDocumentsFolder getDefaultFolder]];
    [self refreshDocuments];
    [self reloadData];
}

-(void)reloadData
{ 
    self.masterView.alpha = 0.0;
    [UIView animateWithDuration:0.1 animations:^{
    
        [self loadData];
        self.masterView.alpha =1.0; 
    }];
}


-(void)refreshFreeSpace
{
    float freeSpace = [DocumentsCache docFolderFreeSpace:MYDOCUMENTS forMaxDimension:MAX_DIM_MIEIDOC];
    NSString *freeSpaceText = [NSString stringWithFormat:NSLocalizedStringFromTable(@"myDocsFreeSpace", @"Documents", nil), freeSpace];
    self.freeSpaceLabel.text = freeSpaceText;
}


-(NSString *)getDocumentsNumber:(int)count{
    NSString *documentsLabel;
    switch (count) {
        case 0:
            documentsLabel = NSLocalizedStringFromTable(@"noDocuments", @"Documents", nil);
            break;
        case 1:
            documentsLabel = [NSString stringWithFormat:@"%d %@", count,NSLocalizedStringFromTable(@"document", @"Documents", nil)];
            break;
            
        default:
            documentsLabel = [NSString stringWithFormat:@"%d %@", count, NSLocalizedStringFromTable(@"documents", @"Documents", nil)];
            break;
    }
    return documentsLabel;
}

    


-(void)loadData{

    int row = 0;
    int column = 0;

    //folder
    
     for(int i = 0; i < _itemFolderList.count; ++i) {

         CGRect newRectangle =CGRectMake(column*180+20, row*180+20, 160, 160);

         FolderThumbView *button = [[FolderThumbView alloc]initWithFrame:newRectangle];
    
         MyDocumentsFolder *folder = [_itemFolderList objectAtIndex:i];
         
                     [button setExclusiveTouch:YES];
                     [button setBackgroundColor:[UIColor clearColor]];
         button.tag = [[folder folderId]intValue]; 

                     
                     // Image
                     button.folderImage = [[UIImageView alloc]initWithFrame:CGRectMake(30., 10, 100., 100.)];
         if (folder.defaultFolder) {
             button.folderImage.image = [UIImage imageNamed:@"defaultFolder"];
         }else {
            // NSString *folderTag
             if(folder.color!=nil){
             button.folderImage.image = [UIImage imageNamed:[NSString stringWithFormat:[NSString stringWithFormat:@"%@%@", folder.color,@"-folder",nil]]];
             }
             else {
                button.folderImage.image = [UIImage imageNamed:@"0-folder"];
             }             
         }            
         // [button.folderImage release];
         // determine the size of the reflection to create
         
         NSUInteger reflectionHeight = button.folderImage.bounds.size.height * kDefaultReflectionFraction_f;
         
         // Ref Image
         button.folderRefImage = [[UIImageView alloc]initWithFrame:CGRectMake(30., 85, 100., reflectionHeight)];
         
         // create the reflection image and assign it to the UIImageView
         button.folderRefImage.image = [button reflectedImage:button.folderImage withHeight:reflectionHeight];
         button.folderRefImage.alpha = 1;
         
         [button addSubview:button.folderRefImage];
         [button addSubview:button.folderImage];

   //      [button.folderRefImage release];

                     // Label
                     button.folderName = [[UILabel alloc] initWithFrame:CGRectMake(0., 110., 160., 20.)];
                     button.folderName.text = folder.name;
                     button.folderName.textColor = [UIColor whiteColor];
                     button.folderName.textAlignment = UITextAlignmentCenter;
                     button.folderName.font = [UIFont boldSystemFontOfSize:14.];
                     button.folderName.backgroundColor = [UIColor clearColor];
                     [button addSubview:button.folderName];
       //              [button.folderName release];
                     button.documentsNumber = [[UILabel alloc] initWithFrame:CGRectMake(0., 125., 160., 20.)];
    
                button.documentsNumber.text = [self getDocumentsNumber:[folder.documents count]];
                button.documentsNumber.textColor = [UIColor whiteColor];
                button.documentsNumber.textAlignment = UITextAlignmentCenter;
                button.documentsNumber.font = [UIFont systemFontOfSize:13.0];
                button.documentsNumber.backgroundColor = [UIColor clearColor];
                [button addSubview:button.documentsNumber];
         
         //open folder
         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:button action:@selector(tapGestureAction:)];
         [tap setNumberOfTapsRequired:2];
         tap.delegate = button;
         [button addGestureRecognizer:tap];
         
         
         //delete or rename
         UISwipeGestureRecognizer *swipeR = [[UISwipeGestureRecognizer alloc]initWithTarget:button action:@selector(swipeGestureActionRight:)];
         [swipeR setDirection:(UISwipeGestureRecognizerDirectionRight)];
         swipeR.delegate = button;
         [button addGestureRecognizer:swipeR];
         
         UISwipeGestureRecognizer *swipeL = [[UISwipeGestureRecognizer alloc]initWithTarget:button action:@selector(swipeGestureActionLeft:)];
         [swipeL setDirection:(UISwipeGestureRecognizerDirectionLeft)];
         swipeL.delegate = button;
         [button addGestureRecognizer:swipeL];

         [masterView addSubview:button]; 
         if (column == 3) {
                           column = 0;
                             row++;
                         } else {
                             column++;
            }
     }
    
    for(int j = 0; j < _itemDocList.count; ++j) {
        
        CGRect newRectangle =CGRectMake(column*180+20, row*180+20, 160, 160);
        
        MyDocument *document = [_itemDocList objectAtIndex:j];
        DocumentThumbView *button = [[DocumentThumbView alloc]initWithFrame:newRectangle];
        [button setExclusiveTouch:YES];
                
      //  button.backgroundColor = [UIColor greenColor];
        
        // Image
        button.docImage = [[UIImageView alloc]initWithFrame:CGRectMake(35, 6., 90.,127.)];
            
        // marked
        if([document.marked boolValue]){
        button.docMarked = [[UIImageView alloc]initWithFrame:CGRectMake(111, 5, 10., 16.)];
        button.docMarked.tag = 333;
        }
    
        NSString *localFilePath = [DocumentsCache localFilePathFromDoc:document];
        NSString *newURL = [[NSString stringWithFormat:@"file://localhost%@",localFilePath] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
        
        // determine the size of the reflection to create
        NSUInteger reflectionHeight = button.docImage.bounds.size.height * kDefaultReflectionFraction;
        
        // Reflected Image
        button.docRefImage = [[UIImageView alloc]initWithFrame:CGRectMake(35, 134., 90., reflectionHeight)];
        
        // Loading Image
        UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(35, 6., 90.,127.)];
        [activity setBackgroundColor:[UIColor clearColor]];
        [activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
        [activity setHidesWhenStopped:YES];
        [activity startAnimating];
        [button addSubview:activity];
        [button setActivityView:activity];
        
        if ([document.fileType isEqualToString:@"pdf"] || [document.fileType isEqualToString:@"pages"]) {
            
            if([document image]==nil){
                UIImage *thumbImage = [self getThumb:newURL setW:90 setH:127];
                button.docImage.image = thumbImage;
                UIImage *thumbImageRef = [button reflectedImage:button.docImage withHeight:reflectionHeight];
                button.docRefImage.image = thumbImageRef;
                NSData *imageData = UIImagePNGRepresentation(thumbImage);
                NSData *imageRefData = UIImagePNGRepresentation(thumbImageRef);
                [document setValue:imageData forKey:@"image"];
                [document setValue:imageRefData forKey:@"imageRef"];
                [(AppDelegate *)[[UIApplication sharedApplication] delegate] saveContext];     
            }else {
                button.docImage.image = [UIImage imageWithData:[document valueForKey:@"image"]];
                button.docRefImage.image = [UIImage imageWithData:[document valueForKey:@"imageRef"]];
            }
                [button.activityView stopAnimating];                
                }         
                else {
                if([document image]==nil){
                [button performSelectorOnMainThread:@selector(getMSThumb:) withObject:[NSURL URLWithString:newURL] waitUntilDone:NO];
                }else {
                    button.docImage.image = [UIImage imageWithData:[document valueForKey:@"image"]];
                    button.docRefImage.image = [UIImage imageWithData:[document valueForKey:@"imageRef"]];
                    [button.activityView stopAnimating];                
                }
                        }        
        // create the reflection image and assign it to the UIImageView
        button.docRefImage.alpha = 0.5;
        button.docMarked.image = [UIImage imageNamed:@"Mark-Y"];
        

        [button addSubview:button.docRefImage];
        [button addSubview:button.docImage];
        [button addSubview:button.docMarked];
        
        // Label
        button.docName = [[UILabel alloc] initWithFrame:CGRectMake(0., 145., 160., 20.)];
        button.docName.text = document.title;
        button.docName.textColor = [UIColor whiteColor];
        button.docName.textAlignment = UITextAlignmentCenter;
        button.docName.font = [UIFont boldSystemFontOfSize:13.5];
        button.docName.backgroundColor = [UIColor clearColor];
        [button addSubview:button.docName];
		button.tag = [[document documentId]intValue]; 
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:button action:@selector(longGestureAction:)];
        longPress.delegate = button;
        [button addGestureRecognizer:longPress];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:button action:@selector(tapGestureAction:)];
        [tap setNumberOfTapsRequired:2];
        tap.delegate = button;
        [button addGestureRecognizer:tap]; 
        
        UISwipeGestureRecognizer *swipeR = [[UISwipeGestureRecognizer alloc]initWithTarget:button action:@selector(swipeGestureActionRight:)];
        [swipeR setDirection:(UISwipeGestureRecognizerDirectionRight)];
        swipeR.delegate = button;
        [button addGestureRecognizer:swipeR];
        
        UISwipeGestureRecognizer *swipeL = [[UISwipeGestureRecognizer alloc]initWithTarget:button action:@selector(swipeGestureActionLeft:)];
        [swipeL setDirection:(UISwipeGestureRecognizerDirectionLeft)];
        swipeL.delegate = button;
        [button addGestureRecognizer:swipeL];
        
        button.droppableDelegate = masterView;   
                        
        [masterView addSubview:button];
        
		if (column == 3) {
			column = 0;
			row++;
		} else {
			column++;
		}
    }
     [masterView setContentSize:CGSizeMake(660, (row+1) * 180 + 20)];
}

- (void)viewDidUnload
{
    [self setSelectedImage:nil];
    [self setSelectedTitle:nil];
    [self setSelectedType:nil];
    [self setSelectedUpdatedate:nil];
    [self setSelectedSize:nil];
    [self setSelectedTitle:nil];
    [self setSelectedImageRef:nil];
    [self setTagColor1:nil];
    [self setTagColor2:nil];
    [self setTagColor3:nil];
    [self setTagColor4:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ((interfaceOrientation == UIInterfaceOrientationPortrait) | (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)) {    // Or whatever orientation it will be presented in.
        return NO;
    }
    return YES;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
